package com.itheima.leadnews.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.article.pojo.ArticleDoc;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dto.ApAssociateWordDto;
import com.heima.model.search.dto.SearchDto;
import com.heima.model.search.pojo.ApAssosiateWords;
import com.heima.model.search.pojo.ApUserSearch;
import com.heima.utils.common.ThreadLocalUtils;
import com.itheima.leadnews.search.service.ApUserSearchService;
import com.itheima.leadnews.search.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(SearchDto dto) throws IOException {
        /**
         * 保存搜索历史
         */
        //判断是否游客登录
        if (ThreadLocalUtils.getUserId() != 0) {
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setUserId(ThreadLocalUtils.getUserId());
            apUserSearch.setKeyword(dto.getSearchWords());
            apUserSearch.setCreatedTime(new Date());
            apUserSearchService.saveApUserSearch(apUserSearch);
        }

        SearchRequest searchRequest = new SearchRequest("app_info_article");
        //组合查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //must并且连接
        boolQueryBuilder.must(QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content"));
        //判断是上滑还是第一次搜索
        if (dto.getMinBehotTime().before(new Date())) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        }
        //设置高亮
        HighlightBuilder highlighterBuilder = new HighlightBuilder();
        highlighterBuilder.field("title");
        highlighterBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlighterBuilder.postTags("</font>");
        searchRequest.source().highlighter(highlighterBuilder);
        searchRequest.source().query(boolQueryBuilder)
                .sort("publishTime", SortOrder.DESC)
                .from(0)
                .size(dto.getPageSize());

        SearchResponse result = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = result.getHits().getHits();
        List<ArticleDoc> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            ArticleDoc articleDoc = JSON.parseObject(sourceAsString, ArticleDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("title");
            if (highlightField != null) {
                Text[] fragments = highlightField.getFragments();
                Text fragment = fragments[0];
                articleDoc.setTitle(fragment.toString());
            }
            list.add(articleDoc);
        }
        return ResponseResult.okResult(list);
    }

    /**
     * 自动联想
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult associateSearch(ApAssociateWordDto dto) throws IOException {
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        suggestBuilder.addSuggestion("suggest",
                SuggestBuilders.completionSuggestion("suggestion")//搜索字段
                        .prefix(dto.getSearchWords())//搜索关键字
                        .size(dto.getPageSize())//显示条数
                        .skipDuplicates(true));//去重
        searchRequest.source().suggest(suggestBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        List<String> list = new ArrayList<>();
        Suggest suggest = search.getSuggest();
        Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> suggestion = suggest.getSuggestion("suggest");
        for (Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> options : suggestion) {
            List<? extends Suggest.Suggestion.Entry.Option> optionsOptions = options.getOptions();
            for (Suggest.Suggestion.Entry.Option optionsOption : optionsOptions) {
                Text text = optionsOption.getText();
                list.add(text.toString());
            }
        }
        List<ApAssosiateWords> apAssosiateWords = list.stream().map(t -> {
            return new ApAssosiateWords(t);
        }).collect(Collectors.toList());
        return ResponseResult.okResult(apAssosiateWords);
    }
}
